
package com.borqs.music.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.borqs.music.R;
import com.borqs.music.executor.MusicExecutor;
import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskAdapter;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.model.VersionInfo;
import com.borqs.music.tasks.QueryVersionInfoTask;
import com.borqs.music.ui.online.OnlineCategoryActivity;
import com.borqs.music.util.AccountUtils;
import com.borqs.music.util.BpcApiUtils;
import com.borqs.music.util.MyLogger;

public class MainTabActivity extends TabActivity implements OnClickListener {
    private static final MyLogger logger = MyLogger.getLogger("MainTabActivity");
    private final static String TAB_SPEC_PERSONAL = "personal";
    private final static String TAB_SPEC_CATEGORY = "category";
    private final static String TAB_SPEC_FEED = "feed";
    private final static String TAB_SPEC_FRIEND = "friend";
    private static boolean mIsInitVersionChecked = false;

    private TabHost mTabHost;
    private TextView mPersonalView;
    private TextView mCategoryView;
    private TextView mFeedsView;
    private TextView mFriendsView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_tabhost);

        initTabs();

        IntentFilter f = new IntentFilter();
        f.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
        f.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
        f.addDataScheme("file");
        registerReceiver(mScanListener, f);
        
        SignupUploadActivity.selfCheck(getApplicationContext());
        if (!mIsInitVersionChecked) {
            mIsInitVersionChecked = true;
            String ticket = AccountUtils.getUserData(this,
                    AccountUtils.BORQS_ACCOUNT_OPTIONS_KEY_SESSION);
            QueryVersionInfoTask task = new QueryVersionInfoTask(mTaskListener, ticket);
            MusicExecutor.getInstance().execute(task);
        }
    }

    private TaskListener mTaskListener = new TaskAdapter() {
        public void onDone(Task task) {
            Message msg = mHandler.obtainMessage(MSG_GET_VERSION);
            msg.obj = task.getResult();
            mHandler.sendMessageDelayed(msg, 500);
        };
    };

    private static final int MSG_GET_VERSION = 1;
    private static final int MSG_UPDATE_MAX = 2;
    private static final int MSG_UPDATE_PROGRESS = 3;
    private static final int MSG_DOWNLOAD_DONE = 4;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_GET_VERSION:
                    VersionInfo version = (VersionInfo)msg.obj;
                    if(checkVersionInfo(version)){
                        double downloadedSize = (double) version.getFileSize() / 1024 / 1024;
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(BUNDLE_KEY_VERSION, version);
                        bundle.putDouble(BUNDLE_KEY_DOWNLOADSIZE, downloadedSize);
                        showDialog(DIALOG_PROMPT_NEW_VERSION, bundle);
                    }
                    break;
                case MSG_UPDATE_MAX:
                    mProgressDialog.setMax(msg.arg1);
                    break;
                case MSG_UPDATE_PROGRESS:
                    mProgressDialog.setProgress(msg.arg1);
                    break;
                case MSG_DOWNLOAD_DONE:
                    dismissDialog(DIALOG_DOWNLOAD);
                    break;
            }
        }
    };

    private static final String BUNDLE_KEY_VERSION = "version";
    private static final String BUNDLE_KEY_DOWNLOADSIZE = "downloadsize";
    
    private boolean checkVersionInfo(VersionInfo version) {
        try {
            PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(),
                    PackageManager.PERMISSION_GRANTED);
            if (version.getVersionCode() > pinfo.versionCode) {
                return true;
            }
        } catch (NameNotFoundException e) {
            logger.e(e.getMessage());
        }
        return false;
    }

    private void downloadNewVersion(final VersionInfo version) {
        File dir = new File(Environment.getExternalStorageDirectory().getPath(),
                "borqs/borqsmusic/apk/");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        final File file = new File(dir.getAbsolutePath(),
                "borqsmusic_" + version.getVersionCode() + ".apk");
        if (file.isFile() && file.exists()) {
            if (file.length() == version.getFileSize()) {
                startInstallAPKActivity(file);
                return;
            } else {
                file.delete();
            }
        }

        showDialog(DIALOG_DOWNLOAD);
        new Thread() {
            @Override
            public void run() {
                try {
                    file.createNewFile();
                    FileOutputStream fileOutput = new FileOutputStream(
                            file);
                    URL url = new URL(version.getFileUrl());
                    HttpURLConnection con = (HttpURLConnection) url
                            .openConnection();
                    con.setRequestMethod("GET");
                    con.setDoOutput(true);
                    con.connect();

                    InputStream inputStream = con.getInputStream();
                    int totalSize = con.getContentLength();
                    Message msg = mHandler.obtainMessage(MSG_UPDATE_MAX);
                    msg.arg1 = totalSize / 1024;
                    mHandler.sendMessage(msg);
                    
                    int downloadedSize = 0;
                    byte[] buffer = new byte[1024 * 4];
                    int bufferLength = 0;
                    while ((bufferLength = inputStream.read(buffer)) > 0) {
                        fileOutput.write(buffer, 0, bufferLength);
                        downloadedSize += bufferLength;
                        mHandler.removeMessages(MSG_UPDATE_PROGRESS);
                        msg = mHandler.obtainMessage(MSG_UPDATE_PROGRESS);
                        msg.arg1 = downloadedSize / 1024;
                        mHandler.sendMessage(msg);
                    }
                    fileOutput.close();
                    inputStream.close();
                    con.disconnect();
                    if (downloadedSize >= totalSize) {
                        msg = mHandler.obtainMessage(MSG_DOWNLOAD_DONE);
                        mHandler.sendMessage(msg);
                        startInstallAPKActivity(file);
                    } else {
                        file.delete();
                    }

                } catch (MalformedURLException e) {
                    logger.e(e.getMessage());
                } catch (ProtocolException e) {
                    logger.e(e.getMessage());
                } catch (IOException e) {
                    logger.e(e.getMessage());
                } finally {
                    Message msg = mHandler.obtainMessage(MSG_DOWNLOAD_DONE);
                    mHandler.sendMessage(msg);
                }
            }
        }.start();

    }

    private void startInstallAPKActivity(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }
    
    private void initTabs() {
        mTabHost = getTabHost();

        // Personal
        mPersonalView = (TextView) findViewById(R.id.bottom_shortcut_personal);
        mPersonalView.setTag(TAB_SPEC_PERSONAL);
        mPersonalView.setOnClickListener(this);
        TabSpec iAppHost = mTabHost.newTabSpec(TAB_SPEC_PERSONAL);
        iAppHost.setIndicator(TAB_SPEC_PERSONAL);
        Intent ipersonal = new Intent(this, MyMusicActivity.class);
        iAppHost.setContent(ipersonal);
        mTabHost.addTab(iAppHost);

        // Category
        mCategoryView = (TextView) findViewById(R.id.bottom_shortcut_category);
        mCategoryView.setTag(TAB_SPEC_CATEGORY);
        mCategoryView.setOnClickListener(this);
        TabSpec iappPoolHost = mTabHost.newTabSpec(TAB_SPEC_CATEGORY);
        iappPoolHost.setIndicator(TAB_SPEC_CATEGORY);
        Intent icategory = new Intent(this, OnlineCategoryActivity.class);
        iappPoolHost.setContent(icategory);
        mTabHost.addTab(iappPoolHost);

        // Feeds
        mFeedsView = (TextView) findViewById(R.id.bottom_shortcut_feed);
        mFeedsView.setTag(TAB_SPEC_FEED);
        mFeedsView.setOnClickListener(this);
        // No need add a tab

        // Friends
        mFriendsView = (TextView) findViewById(R.id.bottom_shortcut_friend);
        mFriendsView.setTag(TAB_SPEC_FRIEND);
        mFriendsView.setOnClickListener(this);
        // No need add a tab

        setActiveTab(TAB_SPEC_PERSONAL);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mScanListener);
    }

    @Override
    public void onClick(View view) {
        String tagClicked = (String) view.getTag();

        if (tagClicked == TAB_SPEC_FRIEND) {
            // Call BPC Friends
            String userId = AccountUtils.getAccountId(this);
            BpcApiUtils.startFriendsActivity(this, userId);
            return;
        }

        if (tagClicked == TAB_SPEC_FEED) {
            // Call BPC Stream
            BpcApiUtils.startStreamActivity(this);
            return;
        }

        if (tagClicked == TAB_SPEC_CATEGORY || tagClicked == TAB_SPEC_PERSONAL) {
            String currentTag = mTabHost.getCurrentTabTag();
            if (tagClicked != currentTag) {
                setActiveTab(tagClicked);
            }
            return;
        }
    }

    private void setActiveTab(String moveToTab) {
        if (TAB_SPEC_PERSONAL.equals(moveToTab)) {
            mFeedsView.setBackgroundDrawable(null);
            mCategoryView.setBackgroundDrawable(null);
            mPersonalView.setBackgroundResource(R.drawable.tab_foot_bg_light);
            mFriendsView.setBackgroundDrawable(null);
        } else if (TAB_SPEC_CATEGORY.equals(moveToTab)) {
            mFeedsView.setBackgroundDrawable(null);
            mCategoryView.setBackgroundResource(R.drawable.tab_foot_bg_light);
            mPersonalView.setBackgroundDrawable(null);
            mFriendsView.setBackgroundDrawable(null);
        } else if (TAB_SPEC_FEED.equals(moveToTab)) {
            mFeedsView.setBackgroundResource(R.drawable.tab_foot_bg_light);
            mPersonalView.setBackgroundDrawable(null);
            mCategoryView.setBackgroundDrawable(null);
            mFriendsView.setBackgroundDrawable(null);
        } else if (TAB_SPEC_FRIEND.equals(moveToTab)) {
            mFeedsView.setBackgroundDrawable(null);
            mPersonalView.setBackgroundDrawable(null);
            mCategoryView.setBackgroundDrawable(null);
            mFriendsView.setBackgroundResource(R.drawable.tab_foot_bg_light);
        }

        mTabHost.setCurrentTabByTag(moveToTab);
    }

    @Override
    protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
        super.onChildTitleChanged(childActivity, title);
        setTitle(title);
    }

    private final static int DIALOG_SCANNING = 1;
    private final static int DIALOG_PROMPT_NEW_VERSION = 2;
    private final static int DIALOG_DOWNLOAD = 3;
    private ProgressDialog mProgressDialog;

    @Override
    protected Dialog onCreateDialog(int id, final Bundle args) {
        switch (id) {
            case DIALOG_SCANNING:
                // create Dialog for scanning media
                ProgressDialog pDialog = new ProgressDialog(this);
                pDialog.setIcon(android.R.drawable.ic_dialog_info);
                pDialog.setTitle(R.string.dialog_scanning_title);
                pDialog.setMessage(getString(R.string.dialog_scanning_message));
                pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                return pDialog;
            case DIALOG_PROMPT_NEW_VERSION:
                return new AlertDialog.Builder(MainTabActivity.this)
                        .setIcon(R.drawable.dialog_question)
                        .setTitle(R.string.dialog_new_version_tile)
                        .setMessage(
                                getString(R.string.dialog_new_version_message,
                                        args.getDouble(BUNDLE_KEY_DOWNLOADSIZE)))
                        .setNeutralButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        downloadNewVersion((VersionInfo) args
                                                .getParcelable(BUNDLE_KEY_VERSION));
                                    }
                                }).setNegativeButton(android.R.string.cancel, null).create();
            case DIALOG_DOWNLOAD:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
                mProgressDialog.setTitle(R.string.dialog_download_title);
                mProgressDialog.setMessage(getString(R.string.dialog_download_message));
                mProgressDialog.setCancelable(true);
                mProgressDialog.setProgress(0);
                return mProgressDialog;
            default:
                break;
        }
        return super.onCreateDialog(id, args);
    }

    private BroadcastReceiver mScanListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
                showDialog(DIALOG_SCANNING);
            }
            if (intent.getAction().equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
                removeDialog(DIALOG_SCANNING);
                Toast.makeText(MainTabActivity.this, R.string.scan_completely,
                        Toast.LENGTH_SHORT).show();
            }
        }
    };
}
